/**
 * Copyright (c) 2016-2017, the original author or authors (dysd_2016@163.com).
 * <p>
 * Licensed under the GPL, Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/gpl.html
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.dysd.dao.dialect.impl;

import org.dysd.dao.dialect.IDialect;

/**
 * DB2方言
 * @author linjisong
 * @version 0.0.1
 * @date 2016-11-12
 */
public abstract class Db2 extends AbstractDialect{
	
	private static final IDialect instance = new Db2(){};//唯一实例
	
	/**
	 * 构造函数私有化
	 */
	private Db2(){
		super.setType("db2");
		super.setDriverClassName("com.ibm.db2.jcc.DB2Driver");
	}
	
	/**
	 * 获取唯一实例
	 */
	public static IDialect getInstance() {
		return instance;
	}
	
	/**
	 * 生成计算总记录数的SQL
	 * @param sql
	 * @return
	 */
	public String getTotalSql(String sql) {
		StringBuilder rs = new StringBuilder();
		rs.append("select count(1) total_ from (").append(sql).append(") total_ ");
		return rs.toString();
	}
	
	/**
	 * 获取查询指定范围记录的SQL
	 * @param sql
	 * @param offset
	 * @param limit
	 * @return
	 */
	public String getScopeSql(String sql, long offset, int limit) {
		StringBuilder scope = new StringBuilder();    
		scope.append("select * from ( select row_.*, row_number() over() rownum_ from ( ");    
		scope.append(sql); 
		scope.append(" ) row_ ) a where rownum_ > ").append(offset)
			 .append(" and rownum_ <= ").append(offset + limit);    
		return scope.toString();
	}
}
